package org.ruiyichen.guizhou.agr.ui.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.gson.reflect.TypeToken;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseFragment;
import org.ruiyichen.guizhou.agr.base.DataManger;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.bean.mode.HomeDeviceModel;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.imp.IIrrigatedAreaFilter;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.activity.HomeActivity;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.utils.ListUtil;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制设备
 */
public class ControlDeviceFragment extends BaseFragment implements View.OnClickListener {

    PieChart chart;

    ArrayList<PieEntry> entries = new ArrayList<>();

    @Override
    public void onResume() {
        super.onResume();
        if (!getUserVisibleHint()) {
            return;
        }
        initData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            bHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initData();
                }
            }, 500);
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.df_fragment_control_device, container, false);
            bOkHttpManager = new OkHttpManager(getActivity(), bHandler);
            initViews();
            initEvents();
            initData();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        return mRootView;
    }

    private void initViews() {

        chart = mRootView.findViewById(R.id.chart1);
        chart.setUsePercentValues(true);
        chart.getDescription().setEnabled(false);
        chart.setExtraOffsets(5, 10, 5, 5);

        chart.setDragDecelerationFrictionCoef(0.95f);

        //chart.setCenterTextTypeface(tfLight);
        chart.setCenterText(generateCenterSpannableText());

        chart.setDrawHoleEnabled(true);
        chart.setHoleColor(Color.WHITE);

        chart.setTransparentCircleColor(Color.WHITE);
        chart.setTransparentCircleAlpha(110);

        chart.setHoleRadius(58f);
        chart.setTransparentCircleRadius(61f);

        chart.setDrawCenterText(true);

        chart.setRotationAngle(0);
        // enable rotation of the chart by touch
        chart.setRotationEnabled(true);
        chart.setHighlightPerTapEnabled(true);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
        chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {

            }

            @Override
            public void onNothingSelected() {

            }
        });

        chart.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // entry label styling
        chart.setEntryLabelColor(Color.WHITE);
//        chart.setEntryLabelTypeface(tfRegular);
        chart.setEntryLabelTextSize(12f);

//        setData(5, 5);
    }

    private final String[] parties = new String[]{
            "未设定", "空闲中", "运行中", "人工设定中", "未绑定"
    };

    private final int[] colors = new int[]{
            Color.parseColor("#4cb1ff"),
            Color.parseColor("#ff0000"),
            Color.parseColor("#5ec778"),
            Color.parseColor("#ffaf38"),
            Color.parseColor("#707070")
    };

    private void setData(List<HomeDeviceModel> list) {
        entries.clear();
        if (ListUtil.isEmpty(list)) {
            return;
        }
        int total = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null) {
                total += StrUtil.parseInt(list.get(i).stateValue);
            }
        }
        if (total == 0) {
            return;
        }
        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null) {
                entries.add(new PieEntry(StrUtil.parseInt(list.get(i).stateValue) * 1.0f / total,
                        list.get(i).stateName,
                        getResources().getDrawable(R.drawable.df_chart_star)));
            }
        }

        PieDataSet dataSet = new PieDataSet(entries, "设备运行数据");
        dataSet.setDrawIcons(false);
        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);
        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter(chart));
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
//        data.setValueTypeface(tfLight);
        chart.setData(data);
        // undo all highlights
        chart.highlightValues(null);
        chart.invalidate();
    }

    private SpannableString generateCenterSpannableText() {
        String title = "数字稻田";
        String left = "最终解释权归";
        String company = "腾色智能科技";
        SpannableString s = new SpannableString(title + "\n" + left + company);
        s.setSpan(new RelativeSizeSpan(1.7f), 0, title.length(), 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), title.length(), title.length() + left.length()
                + 1, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), title.length(), title.length() + left
                .length() + 1, 0);
        s.setSpan(new RelativeSizeSpan(0.8f), title.length(), title.length() + left.length() + 1, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), title.length() + left.length() + 1, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), title.length() + left
                .length() + 1, s.length
                (), 0);
        return s;
    }


    private void initEvents() {
    }

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_normal_other:
                break;
        }
    }

    private HomeActivity getCustomActivity() {
        return (HomeActivity) getActivity();
    }

    private void initData() {
        Map<String, String> body = new HashMap<>();
        bOkHttpManager.httpRequest(Constant.RequestType.SELECT_DEVICE_STATE, Constant.Http.GET, body,
                false, new
                TypeToken<Response<List<HomeDeviceModel>, Void>>() {
                }.getType(), true, false);
    }

    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.SELECT_DEVICE_STATE) {
                    Response<List<HomeDeviceModel>, Void> result = (Response<List<HomeDeviceModel>, Void>) response;
                    if (result.isSuccess()) {
                        setData(result.getData());
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                }
            }
        }
    }
}

